#include "NosepieceOlympusREMCB.h"
#include <QTextStream>

NosepieceOlympusREMCB::NosepieceOlympusREMCB(QObject *parent)
    : QObject(parent),
      m_comPort("COM1"),
      m_baudRate(QSerialPort::Baud9600),
      m_dataBits(QSerialPort::Data8),
      m_parity(QSerialPort::NoParity),
      m_stopBits(QSerialPort::OneStop),
      m_lens(0),
      m_serialPort(nullptr)
{

}

void NosepieceOlympusREMCB::login()
{
    if(m_serialPort)
    {
        m_serialPort->close();
        delete m_serialPort;
    }
    m_serialPort = new QSerialPort(m_comPort, this);
    if(m_serialPort->open(QIODevice::ReadWrite))
    {
        qDebug() << m_baudRate;
        qDebug() << m_dataBits;
        qDebug() << m_parity;
        qDebug() << m_stopBits;
        m_serialPort->setBaudRate(m_baudRate);
        m_serialPort->setDataBits(static_cast<QSerialPort::DataBits> (m_dataBits));
        m_serialPort->setParity(static_cast<QSerialPort::Parity>(m_parity));
        m_serialPort->setStopBits(static_cast<QSerialPort::StopBits>(m_stopBits));
        m_serialPort->setFlowControl(QSerialPort::NoFlowControl);
        m_serialPort->clearError();
        m_serialPort->clear();

        cmd("1LOG IN\r\n");
        cmd("1OB 1\r\n");
    }
}

void NosepieceOlympusREMCB::loadSettings(QSettings &settings)
{
    m_comPort = settings.value("Nosepiece/SerialPort", "COM6").toString();
    m_baudRate = settings.value("Nosepiece/BaudRate", QSerialPort::Baud9600).toInt();
    m_dataBits = settings.value("Nosepiece/DataBits", QSerialPort::Data8).toInt();
    m_parity = settings.value("Nosepiece/Parity", QSerialPort::EvenParity).toInt();
    m_stopBits = settings.value("Nosepiece/StopBits", QSerialPort::OneStop).toInt();
}

void NosepieceOlympusREMCB::cmd(QString str)
{
    if(m_serialPort && m_serialPort->isWritable())
    {
        m_serialPort->write(str.toLocal8Bit());
        //QTextStream stream(m_serialPort);
        qDebug() << str;
        //stream << str;
        if(!m_serialPort->waitForReadyRead(100))
        {
            return;
        }
        //QString ret = stream.readLine();
    }
}

void NosepieceOlympusREMCB::setLens(int lens)
{
    lens++; // Olympus 的物镜转盘是从 1 开始计数的。所以这里要 + 1
    int lowerLimit = 1;
    int upperLimit = 5;
    lens = qBound(lowerLimit, lens, upperLimit);
    cmd(QString("1OB %1\r\n").arg(lens));
    if(m_lens != lens)
    {
        m_lens = lens;
    }
}

void NosepieceOlympusREMCB::setLens(int oldLens, int newLens)
{
    setLens(newLens);
}

void NosepieceOlympusREMCB::forward()
{
    if(m_lens < 4)
    {
        setLens(m_lens + 1);
    }
    //m_nosepiece->dynamicCall("Forward()");
}

void NosepieceOlympusREMCB::reverse()
{
    if(m_lens > 0)
    {
        setLens(m_lens - 1);
    }
    //m_nosepiece->dynamicCall("Reverse()");
}
